package com.zzptc.sky.baidudemo.services;


import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zzptc.sky.baidudemo.R;
import com.zzptc.sky.baidudemo.activities.CheckUpdateActivity;
import com.zzptc.sky.baidudemo.fragments.UpdateVersionFragment;
import com.zzptc.sky.baidudemo.utils.MyApplication;
import com.zzptc.sky.baidudemo.utils.MyUntils;

import java.io.File;

import okhttp3.Call;
import okhttp3.Request;

public class MyDownLoadService extends Service {
    private NotificationCompat.Builder builder;
    private NotificationManager notificationManager;

    public MyDownLoadService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String url = null;
        if (intent != null){
            url = intent.getStringExtra("apkurl");
        }
        createNotification();
        File file = MyUntils.getDir();
        String strFile = file.getAbsolutePath();
        url = "http://192.168.1.137:8080/mobileDemo/apk/bdsjws-debug.apk";
        downloadFile(url,file);
        Log.d("222",strFile);
        Log.d("111",url);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void createNotification(){
        notificationManager = (NotificationManager) MyApplication.getContext().getSystemService(NOTIFICATION_SERVICE);
        builder = new NotificationCompat.Builder(MyApplication.getContext());
        builder.setSmallIcon(R.mipmap.logo_small)
                .setContentText("正在下载")
                .setContentTitle("百度手机卫士下载")
                .build();
        notificationManager.notify(0,builder.build());
    }

    private void downloadFile(String url,File file){
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new FileCallBack(file.getAbsolutePath(),"aaa.apk") {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        builder.setContentTitle("下载失败");
                        notificationManager.notify(0,builder.build());
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        builder.setContentTitle("下载成功");
                        builder.setContentText("下载完成");
                        builder.setAutoCancel(true);
                        notificationManager.notify(0,builder.build());

                        //installApk(response);

                        Intent intent = MyUntils.getInstallIntent(response);
                        TaskStackBuilder stackBuilder = TaskStackBuilder.create(MyDownLoadService.this);
                        stackBuilder.addParentStack(CheckUpdateActivity.class);
                        stackBuilder.addNextIntent(intent);
                        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
                        builder.setContentIntent(resultPendingIntent);

                        builder.setProgress(0,0,false);
                        builder.setContentText("请点击安装");
                        builder.setContentTitle("下载完毕");
                        notificationManager.notify(0,builder.build());
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        builder.setProgress(100,(int) (progress*100),false);
                        builder.setContentText("已下载"+(int) (progress*100)+"%");
                        notificationManager.notify(0,builder.build());
                        super.inProgress(progress, total, id);

                    }

                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                    }
                });
    }

    public void installApk(File file){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
        MyApplication.getContext().startActivity(intent);
    }
}
